#include "pressurechart.h"
#include "ui_pressurechart.h"

class Sample {
public:
    unsigned int sis;
    unsigned int dia;
    Sample(int _sis=120,int _dia=80){sis=_sis;dia=_dia;};
};


PressureChart::PressureChart(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::PressureChart)
{
    dbModel = 0;
    ui->setupUi(this);
    showMaximized();
    redraw();
}

PressureChart::~PressureChart()
{
    delete ui;
}

void PressureChart::changeEvent(QEvent *e)
{
    QDialog::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

void PressureChart::setDb(QSqlTableModel *db)
{
    dbModel = db;
}

void PressureChart::redraw()
{

    QVector<Sample> samples;
    samples << Sample(120,80) << Sample(140,90) << Sample(95,75)
            << Sample(140,90) << Sample(150,90) << Sample(135,75)
            << Sample(150,95) << Sample(160,100) << Sample(145,105);
    unsigned int ns = samples.size();
    unsigned int grid = 50;
    unsigned int rad = 6;
    Sample smax(0,0), smin((unsigned int)(-1),(unsigned int)(-1));
    foreach(Sample s, samples)
    {
        if(s.dia < smin.dia) smin.dia = s.dia;
        if(s.dia > smax.dia) smax.dia = s.dia;
        if(s.sis < smin.sis) smin.sis = s.sis;
        if(s.sis > smax.sis) smax.sis = s.sis;
    }

    QPen dia_pen(Qt::red,2);
    QPen sis_pen(Qt::blue,2);
    scene.addRect(0,smin.dia,ns*grid,smax.sis-smin.dia,dia_pen);

    unsigned int d = 0;
    for(unsigned int n = 0 ; n < samples.size() ; n++, d += grid)
    {
        scene.addEllipse(d-rad,samples[n].dia-rad,2*rad,2*rad,dia_pen);
        scene.addEllipse(d-rad,samples[n].sis-rad,2*rad,2*rad,sis_pen);
        if(n)
        {
            scene.addLine(d-grid,samples[n-1].dia,d,samples[n].dia,dia_pen);
            scene.addLine(d-grid,samples[n-1].sis,d,samples[n].sis,sis_pen);
        }
    }
    ui->chart->setScene(&scene);
    //ui->chart->setSceneRect(0-rad*2,smin.dia-rad*2,ns*grid+rad,smax.sis-smin.dia+rad);

    ui->chart->resetMatrix();
    //ui->chart->rotate(180);
    ui->chart->fitInView(0-rad*2,smin.dia-rad*2,ns*grid+2*rad,smax.sis-smin.dia+2*rad,Qt::KeepAspectRatio);
    ui->chart->show();
    //ui->chart->ensureVisible(0-rad*2,smin.dia-rad*2,ns*grid+2*rad,smax.sis-smin.dia+2*rad);

}
